//和用户相关的状态管理 

import { createSlice } from "@reduxjs/toolkit";
import { request, clearToken, getToken, setToken } from "@/utils/index";
import { loginAPI, getProfileAPI } from "@/apis/user";

// 管理用户的登录信息
const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },

    // 同步修改方法
    reducers: {
        // 用户登录时，更新token的值
        setUserLogin(state, action) {
            state.token = action.payload
            // 存入本地
            setToken(action.payload)
        },

        // 存储用户个人信息
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            clearToken()
        }
    }
})

// 解构出actionCreator
const { setUserLogin, setUserInfo, clearUserInfo } = userStore.actions
// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法封装 处理登录逻辑
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm)
        dispatch(setUserLogin(res.data.token))
    }
}

// 获取个人用户信息异步方法
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getProfileAPI()
        dispatch(setUserInfo(res.data))
    }
}
export { fetchLogin, fetchUserInfo, clearUserInfo }

export default userReducer